package kr.co.doriclassic.mypuppystory.searchpuppy;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import kr.co.doriclassic.mypuppystory.R;
import kr.co.doriclassic.mypuppystory.alarmpuppy.PreferenceManager;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ItemParser extends Parser<Item> {
	private ArrayList<Item> item;
	private XmlPullParser parser;
	private Context context;
	private ExpandableListView list;
	ProgressDialog progressDlg;
	PreferenceManager pf;

	public ItemParser(String url, Context context, ExpandableListView list) {
		this.context = context;
		this.list = list;
		new ParsingXML().execute(url);
	}

	@Override
	ArrayList<Item> parseItem(String url) {
		parser = connInfo(url);
		item = new ArrayList<Item>();
		try {
			String tag;
			Item itemClass = null;
			boolean init_filename = false;
			boolean init_kindCd = false;
			boolean init_sexCd = false;
			boolean init_processState = false;
			boolean init_careNm = false;
			boolean init_careTel = false;
			boolean init_popfile = false;
			boolean init_noticeNo = false;
			boolean init_happenDt = false;
			boolean init_happenPlace = false;
			boolean init_noticeSdt = false;
			boolean init_noticeEdt = false;
			boolean init_careAdd = false;
			int parserEvent = parser.getEventType();
			pf = new PreferenceManager(context);
			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				switch (parserEvent) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					// item 불러내기
					if (parser.getName().equalsIgnoreCase("item")) {
						itemClass = new Item();
					}

					if (parser.getName().equalsIgnoreCase("filename")) {
						init_filename = true;
					} else if (parser.getName().equalsIgnoreCase("kindCd")) {
						init_kindCd = true;
					} else if (parser.getName().equalsIgnoreCase("sexCd")) {
						init_sexCd = true;
					} else if (parser.getName()
							.equalsIgnoreCase("processState")) {
						init_processState = true;
					} else if (parser.getName().equalsIgnoreCase("popfile")) {
						init_popfile = true;
					} else if (parser.getName().equalsIgnoreCase("noticeNo")) {
						init_noticeNo = true;
					} else if (parser.getName().equalsIgnoreCase("happenDt")) {
						init_happenDt = true;
					} else if (parser.getName().equalsIgnoreCase("happenPlace")) {
						init_happenPlace = true;
					} else if (parser.getName().equalsIgnoreCase("noticeSdt")) {
						init_noticeSdt = true;
					} else if (parser.getName().equalsIgnoreCase("noticeEdt")) {
						init_noticeEdt = true;
					} else if (parser.getName().equalsIgnoreCase("careNm")) {
						init_careNm = true;
					} else if (parser.getName().equalsIgnoreCase("careTel")) {
						init_careTel = true;
					} else if (parser.getName().equalsIgnoreCase("careAddr")) {
						init_careAdd = true;
					}
					break;
				case XmlPullParser.TEXT:
					if (init_popfile) {
						itemClass.setPopfile(parser.getText());
						init_popfile = false;
					} else if (init_noticeNo) {
						itemClass.setNoticeNo(parser.getText());
						init_noticeNo = false;
					} else if (init_happenDt) {
						itemClass.setHappenDt(parser.getText());
						init_happenDt = false;
					} else if (init_happenPlace) {
						itemClass.setHappenPlace(parser.getText());
						init_happenPlace = false;
					} else if (init_noticeSdt) {
						itemClass.setNoticeSdt(parser.getText());
						init_noticeSdt = false;
					} else if (init_noticeEdt) {
						itemClass.setNoticeEdt(parser.getText());
						init_noticeEdt = false;
					} else if (init_filename) {
						itemClass.setFilename(parser.getText());
						init_filename = false;
					} else if (init_kindCd) {
						itemClass.setKindCd(parser.getText());
						init_kindCd = false;
					} else if (init_sexCd) {
						itemClass.setSexCd(parser.getText());
						init_sexCd = false;
					} else if (init_processState) {
						itemClass.setProcessState(parser.getText());
						init_processState = false;
					} else if (init_careNm) {
						itemClass.setCareNm(parser.getText());
						init_careNm = false;
					} else if (init_careTel) {
						itemClass.setCareTel(parser.getText());
						init_careTel = false;
					} else if (init_careAdd) {
						itemClass.setCareAddr(parser.getText());
						init_careAdd = false;
					}

					break;
				case XmlPullParser.END_TAG:
					tag = parser.getName();
					if (tag.equalsIgnoreCase("item")) {
						item.add(itemClass);
					}
					break;
				}
				parserEvent = parser.next();
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return item;
	}

	public class ParsingXML extends AsyncTask<String, String, ArrayList<Item>> {

		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(context, "Loading",
					"내용을 읽고 있습니다.");
		}

		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			BaseExpandableListAdapter adapter = new ItemAdapter(context, list,
					R.layout.itemrow, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
			if (result.size() < 1) {
				Toast.makeText(context, "검색 결과가 없어요~~", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			return parseItem(params[0]);
		}
	}

	// 변경할것
	public class ItemAdapter extends BaseExpandableListAdapter {

		Context context;
		int layout;
		LayoutInflater inflater;
		ImageView iv;
		String url;

		ArrayList<Item> itemList;
		ExpandableListView listview;
		boolean[] mGroupClickState;
		int lastExpandedGroupPosition = -1;

		private View itemLayout;
		private View childLayout;
		private ImageLoader imageLoader;
		private ViewHolder viewHolder;

		public ItemAdapter(Context context, ExpandableListView listview,
				int layout, ArrayList<Item> result) {
			this.itemList = result;
			this.listview = listview;
			this.context = context;
			this.layout = layout;

			mGroupClickState = new boolean[result.size()];
			for (int i = 0; i < mGroupClickState.length; i++)
				mGroupClickState[i] = false;

			inflater = LayoutInflater.from(context);
		}

		class ViewHolder {
			ImageView filename;
			TextView kindCd;
			TextView sexCd;
			TextView processState;

			ImageView popfile;
			TextView noticeNo;
			TextView happenDt;
			TextView happenPlace;
			TextView noticeSdt;
			TextView noticeEdt;
			TextView careNm;
			Button careTel;
			TextView careAdd;

		}

		@Override
		public int getGroupCount() {
			// Log.d("itemListSize", itemList.size() + "");
			return itemList.size();
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		@Override
		public Object getGroup(int groupPosition) {
			return itemList.get(groupPosition);
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return null;
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			itemLayout = convertView;
			viewHolder = null;

			// 처음 생성되었을 때, 나머지는 재활용(리스트뷰)
			if (itemLayout == null) {
				itemLayout = inflater.inflate(layout, parent, false);

				viewHolder = new ViewHolder();
				viewHolder.filename = (ImageView) itemLayout
						.findViewById(R.id.filename);
				viewHolder.kindCd = (TextView) itemLayout
						.findViewById(R.id.kindCd);
				viewHolder.sexCd = (TextView) itemLayout
						.findViewById(R.id.sexCd);
				viewHolder.processState = (TextView) itemLayout
						.findViewById(R.id.processState);

				itemLayout.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) itemLayout.getTag();
			}
			iv = viewHolder.filename;
			url = itemList.get(groupPosition).getFilename();
			imageLoader = new ImageLoader(context);
			imageLoader.DisplayImage(url, iv);
			String reKindCd[] = itemList.get(groupPosition).getKindCd()
					.split("개] ");
			viewHolder.kindCd.setText(reKindCd[1]);

			if (itemList.get(groupPosition).getSexCd().equals("M"))
				viewHolder.sexCd.setTextColor(Color.BLUE);
			else if (itemList.get(groupPosition).getSexCd().equals("F"))
				viewHolder.sexCd.setTextColor(Color.RED);
			viewHolder.sexCd.setText(itemList.get(groupPosition).getSexCd());

			if (!itemList.get(groupPosition).getProcessState().equals("보호중"))
				viewHolder.processState.setTextColor(context.getResources()
						.getColor(R.color.fontcolor));
			viewHolder.processState.setText(itemList.get(groupPosition)
					.getProcessState());

			// 선택된 것 색상 변경
			if (isExpanded) {
				int color = itemLayout.getResources().getColor(
						R.color.fontcolor);
				itemLayout.setBackgroundColor(color);
			} else {
				itemLayout.setBackgroundColor(Color.TRANSPARENT);
			}

			return itemLayout;
		}

		@Override
		public View getChildView(final int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			childLayout = convertView;
			viewHolder = null;
			if (childLayout == null) {
				childLayout = inflater.inflate(R.layout.itemcontent, parent,
						false);
				viewHolder = new ViewHolder();
				viewHolder.popfile = (ImageView) childLayout
						.findViewById(R.id.popfile);
				viewHolder.noticeNo = (TextView) childLayout
						.findViewById(R.id.noticeNo);
				viewHolder.happenDt = (TextView) childLayout
						.findViewById(R.id.happenDt);
				viewHolder.happenPlace = (TextView) childLayout
						.findViewById(R.id.happenPlace);
				viewHolder.noticeSdt = (TextView) childLayout
						.findViewById(R.id.noticeSdt);
				viewHolder.noticeEdt = (TextView) childLayout
						.findViewById(R.id.noticeEdt);
				viewHolder.careNm = (TextView) childLayout
						.findViewById(R.id.careNm);
				viewHolder.careTel = (Button) childLayout
						.findViewById(R.id.careTel);
				viewHolder.careAdd = (TextView) childLayout
						.findViewById(R.id.careAddr);

				childLayout.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) childLayout.getTag();
			}
			imageLoader = new ImageLoader(context);
			imageLoader.DisplayImage(itemList.get(groupPosition).getPopfile(),
					viewHolder.popfile);
			viewHolder.noticeNo.setText(itemList.get(groupPosition)
					.getNoticeNo());

			String hdt = itemList.get(groupPosition).getHappenDt();
			String reHappenDt = String.format("%4s.%2s.%2s",
					hdt.subSequence(0, 4), hdt.subSequence(4, 6),
					hdt.subSequence(6, 8));
			viewHolder.happenDt.setText(reHappenDt);

			viewHolder.happenPlace.setText(itemList.get(groupPosition)
					.getHappenPlace());

			String sdt = itemList.get(groupPosition).getNoticeSdt();
			String renoticeSdt = String.format("%4s.%2s.%2s",
					sdt.subSequence(0, 4), sdt.subSequence(4, 6),
					sdt.subSequence(6, 8));
			viewHolder.noticeSdt.setText(renoticeSdt);

			String edt = itemList.get(groupPosition).getNoticeEdt();
			String renoticeEdt = String.format("%4s.%2s.%2s",
					edt.subSequence(0, 4), edt.subSequence(4, 6),
					edt.subSequence(6, 8));
			viewHolder.noticeEdt.setText(renoticeEdt);

			viewHolder.careNm.setText(itemList.get(groupPosition).getCareNm());
			viewHolder.careTel.setText(itemList.get(groupPosition).getCareTel()
					+ "\t(버튼 눌러 통화)");
			viewHolder.careAdd.setText(itemList.get(groupPosition)
					.getCareAddr());

			viewHolder.careTel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					context.startActivity(new Intent(
							"android.intent.action.DIAL", Uri.parse("tel:"
									+ itemList.get(groupPosition).getCareTel())));
				}
			});

			return childLayout;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		// 나머지 열린 것 닫기
		@Override
		public void onGroupExpanded(int groupPosition) {
			// Log.e("", "LAST" + lastExpandedGroupPosition + ", CUR : "
			// + groupPosition);
			// TODO Auto-generated method stub
			// 그룹을 클릭했을때 열려져 있는 지 표시하는 화살표 아이콘 위/아래
			mGroupClickState[groupPosition] = !mGroupClickState[groupPosition];
			// 그룹을 클릭했을때 이전그룹이 열려 있으면 닫음
			if (lastExpandedGroupPosition != -1
					&& lastExpandedGroupPosition != groupPosition) {
				listview.collapseGroup(lastExpandedGroupPosition);
				mGroupClickState[lastExpandedGroupPosition] = false;
			}

			lastExpandedGroupPosition = groupPosition;
			super.onGroupExpanded(groupPosition);
		}
	}// ItemAdapter
}
